<script>
import {saveAs} from "file-saver";
import room from "@/views/Room.vue";

export default {

  name: "Room",
  data() {
    return {

      //级联选择器拿到的值
      value: [],
      //级联选择器传输的值
      options: [],
      //级联选择器的选项
      props: {
        value: "id",
        label: "name",
        children: "units"
      },
      //导出所需的id数组
      roomIds: [],
      // 选中的数据条数
      multipleSelection: [],
      //模糊查询表单参数
      formInline: {
        options: '',
        roomStatus: '',
      },

      rules: {
        roomName: [
          {required: true, message: '房屋名称不能为空', trigger: 'blur'},

        ],
        roomAcreage: [
          {required: true, message: '房屋面积不能为空', trigger: 'blur'},
          {pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确格式，可保留两位小数', trigger: ['blur', 'change']}
        ],
        buildingId: [
          {required: true, message: '楼栋/单元名称不能为空', trigger: 'blur'},
        ],
        roomLevel: [
          {required: true, message: '楼层不能为空', trigger: 'blur'},
        ],
        roomStatus: [
          {required: true, message: '房屋状态不能为空', trigger: 'blur'},
        ],
        roomHouseType: [
          {required: true, message: '房屋户型不能为空', trigger: 'blur'},
        ],
      },
      communityId: '',       //所属小区ID
      current: 1,     //当前页码
      size: 2,        //每页数据条数
      pages: 1,        //页面数
      total: 1,        //总数据条数
      rooms: [],   //房屋列表
      roomStatus: [],  //房屋状态列表
      roomHouseType: [],  //房屋户型列表
      room: {
        "roomId": null,
        "unitId": "",
        "buildingId": "",
        "roomLevel": "",
        "roomName": "",
        "roomAcreage": "",
        "roomCost": "",
        "roomStatus": "",
        "roomIsShop": "",
        "roomSCommercialHouse": "",
        "roomHouseType": "",
        "remark": "",
        "communityId": ""
      },
      room1: {
        "roomId": null,
        "unitId": "",
        "buildingId": "",
        "roomLevel": "",
        "roomName": "",
        "roomAcreage": "",
        "roomCost": "",
        "roomStatus": "",
        "roomIsShop": "",
        "roomSCommercialHouse": "",
        "roomHouseType": "",
        "remark": "",
        "communityId": ""
      },
      showSearchForm: true, // 控制搜索表单显示与隐藏的变量
      //房屋表单信息
      dialogFormVisible: false, //表单显示变量
      formLabelWidth: '100px'   // 表单宽度
    }
  },
  methods: {

    reload() {
      location.reload()
    },

    toggleSearch() {
      this.showSearchForm = !this.showSearchForm; // 点击按钮切换显示与隐藏
    },
    //分页查询
    loadRooms(event) {
      this.current = event.current;
      this.size = event.size;
      this.formInline = event.formInline;
      this.communityId = event.communityId;
      const queryParams = {
        current: this.current,
        size: this.size,
        buildingId: this.formInline.options[0],
        unitId: this.formInline.options[1],
        roomStatus: this.formInline.roomStatus,
        communityId: this.communityId
      }
      this.$axios.get("/zyRoom/rooms", {params: queryParams})
          .then(result => {
            if (result.data.code = "200") {
              console.log("************************")
              console.log(result.data.data);
              this.rooms = result.data.data.records;
              this.pages = result.data.data.pages;
              this.total = result.data.data.total;
            }
          })
    },
    handleSizeChange(size) {
      this.size = size;
      this.loadRooms({
        current: this.current,
        size: this.size,
        formInline: this.formInline,
        communityId: this.communityId
      });
    },
    handleCurrentChange(current) {
      this.current = current;
      this.loadRooms({
        current: this.current,
        size: this.size,
        formInline: this.formInline,
        communityId: this.communityId
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getIndex(index) {
      return (this.current - 1) * this.size + index + 1;
    }
    ,
    onSubmit() {
      let formInline = this.formInline;
      console.log("________",formInline)
      this.loadRooms({
        current: 1,
        size: this.size,
        formInline: formInline,
        communityId: this.communityId
      });
    }
    ,

    ClearOnSubmit() {
      this.formInline = {
        options: '',
        roomStatus: ''
      }
      this.loadRooms({
        current: this.current,
        size: this.size,
        formInline: this.formInline,
        communityId: this.communityId
      });
    }

    // clearRoomInformation() {
    //   this.room = {
    //     "roomId": null,
    //     "unitId": "",
    //     "buildingId": "",
    //     "roomLevel": "",
    //     "roomName": "",
    //     "roomAcreage": "",
    //     "roomCost": "",
    //     "roomStatus": "",
    //     "roomIsShopLabel": "",
    //     "roomSCommercialHouseLabel": "",
    //     "roomHouseType": "",
    //     "remark": "",
    //     "communityId": ""
    //   }
    //   // this.value=[]
    //   this.dialogFormVisible = true;
    // }
    ,
    clearForm() {
      this.$refs.form.clearValidate();// 清除表单验证信息
      this.$refs.form.resetFields(); // 重置表单字段
    }
    ,
    saveAndEditStudent(forName) {
      this.$refs[forName].validate(valid => {
            if (valid) {
              //通过id判断是否为null，判断进行添加或更新
              if (this.room.roomId == null) {
                const username = localStorage.getItem("username");
                this.$axios.post("/zyRoom/room/" + username, this.room)
                    .then(result => {
                      if (result.data.code = "200") {
                        this.loadRooms({
                          current: this.current,
                          size: this.size,
                          formInline: this.formInline,
                          communityId: this.communityId
                        });
                        return this.$message({
                          message: '添加成功',
                          type: 'success',
                          duration: 2000
                        });
                      } else {
                        return this.$message.error({
                          message: '添加失败',
                          duration: 2000
                        });
                      }
                    });
              } else {
                const username = localStorage.getItem("username");
                this.$axios.put("/zyRoom/room/" + username, this.room)
                    .then(result => {
                      if (result.data.code = "200") {
                        this.loadRooms({
                          current: this.current,
                          size: this.size,
                          formInline: this.formInline,
                          communityId: this.communityId
                        });
                        return this.$message({
                          message: '修改成功',
                          type: 'success',
                          duration: 2000
                        });
                      } else {
                        return this.$message.error({
                          message: "修改失败",
                          duration: 2000
                        })
                      }
                    })
              }
              this.room = {
                "roomId": null,
                "unitId": "",
                "buildingId": "",
                "roomLevel": "",
                "roomName": "",
                "roomAcreage": "",
                "roomCost": "",
                "roomStatus": "",
                "roomIsShop": "",
                "roomSCommercialHouse": "",
                "roomHouseType": "",
                "remark": "",
                "communityId": ""
              }
            } else {
              this.dialogFormVisible = true;
            }
          }
      )
    }
    ,
    handleClose(done) {
      // 处理逻辑
      this.clearForm();
      // 可以调用done()来关闭dialog，或者不调用done()来阻止关闭
      done();
    },
    //更新回填信息
    editRoom(r) {
      console.log('1111111111111112222', room)
      this.options = [r.buildingId, r.unitId]
      console.log('2222', this.options)
      const room1 = JSON.parse(JSON.stringify(r));
      this.room = room1
      this.dialogFormVisible = true;
    },

    editItem() {
      this.room = this.multipleSelection[0];
      this.editRoom(this.room);
    },

    deleteItem() {
      const roomIds = this.multipleSelection.map(item => item.roomId);
      this.open(roomIds)
    },
    deleteRoom(roomIds) {
      this.$axios.delete("/zyRoom/room/" + roomIds)
          .then(result => {
            if (result.data.code = "200") {
              if (this.multipleSelection.length > 1) {
                if (this.multipleSelection.length == this.rooms.length && this.current > 1) {
                  this.loadRooms({
                    current: this.current - 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else if (this.multipleSelection.length == this.rooms.length && this.current == 1) {
                  this.loadRooms({
                    current: this.current + 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else {
                  this.loadRooms({
                    current: this.current,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                }
              } else {
                if (this.rooms.length == 1 && this.current > 1) {
                  this.loadRooms({
                    current: this.current - 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else if (this.rooms.length == 1 && this.current == 1) {
                  this.loadRooms({
                    current: this.current + 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else {
                  this.loadRooms({
                    current: this.current,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                }
              }
            }
          })

    },

    open(roomId) {
      this.$confirm('是否确认删除房屋编号为' + '"' + roomId + '"' + '的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRoom(roomId);
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //导出到excel
    exportExcel() {
      this.$prompt('请输入导出文件名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$axios.get("/zyRoom/export?roomIds=" + this.roomIds, {responseType: 'arraybuffer'})
            .then(result => {
              const blob = new Blob([result.data], {type: 'applicationnd.openxmlformats-officedocument.spreadsheetml.sheet'});
              saveAs(blob, value + '.xlsx');
              this.loadRooms({
                current: this.current,
                size: this.size,
                formInline: this.formInline,
                communityId: this.communityId
              });
              this.$message({
                type: 'success',
                message: '文件：' + value + '导出成功！'
              });
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导出！'
        });
      });
    },

    //获取多行数据
    selectRoomOneId(val) {
      this.roomIds = [];
      for (let i = 0; i < val.length; i++) {
        this.roomIds[i] = val[i].roomId;
      }
      console.log(this.roomIds)

    },
    //获取全部行数据
    selectRoomAllIds(val) {
      this.roomIds = [];
      for (let i = 0; i < val.length; i++) {
        this.roomIds[i] = val[i].roomId;
      }
      console.log(this.roomIds)
    },

    //级联表单触发方法
    handleChange(value) {
      this.room.buildingId = value[0]
      console.log("1111111111", this.room.buildingId)
      this.room.unitId = value[1]
      console.log("222222222", this.room.unitId)
    },

    //加载房屋状态
    loadRoomStatus() {
      this.$axios.get("/sysDictData-find?dictType=zy_room_state")
          .then(result => {
            console.log(result.data.data)
            this.roomStatus = result.data.data;
          })
    },

    //加载房屋户型
    loadRoomHouseType() {
      this.$axios.get("/sysDictData-find?dictType=zy_house_state")
          .then(result => {
            console.log("^^^^^^^^^", result.data.data)
            this.roomHouseType = result.data.data;
          })
    },

    //加载楼栋和单元
    loadBuildingsAndUnits() {
      this.$axios.get("/zyRoom/buildingsAndUnits")
          .then(result => {
            console.log(result.data.data)
            this.value = result.data.data;
          })
    },

  },
  mounted() {
    this.communityId = localStorage.getItem("comId")
    room.communityId = this.communityId
    this.loadRooms({
      current: this.current,
      size: this.size,
      formInline: this.formInline,
      communityId: this.communityId
    });
    this.loadRoomStatus();
    this.loadRoomHouseType();
    this.loadBuildingsAndUnits();
  }
}
</script>
<template>
  <div id="room">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" v-show="showSearchForm">
      <el-form-item label="楼栋/单元">
        <!--        <el-input v-model="formInline.roomName" placeholder="请输入房屋名称" size="small"></el-input>-->
        <el-cascader
            v-model="formInline.options"
            :options="value"
            :props="props"
            @change="handleChange">
        </el-cascader>
      </el-form-item>

      <el-form-item label="房屋状态">
        <el-select v-model="formInline.roomStatus" placeholder="请选择">
          <el-option
              v-for=" item in roomStatus"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue">
          </el-option>
        </el-select>
        <!--        <el-input v-model="formInline.roomStatus" placeholder="请输入房屋编码" size="small"></el-input>-->
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit" size="small" style="background-color: #20B2AA">
          <i class="el-icon-search" style="width: 20px"></i>搜索
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button @click="ClearOnSubmit" size="small">
          <i class="el-icon-refresh-right" style="width: 20px"></i>重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" size="small" @click="editRoom(room1)">
      <i class="el-icon-plus" style="width: 20px"></i>新增
    </el-button>
    <el-button @click="editItem" type="success" size="small" :disabled="multipleSelection.length !== 1">
      <i class="el-icon-edit" style="width: 20px"></i>修改
    </el-button>
    <el-button type="danger" size="small" :disabled="multipleSelection.length == 0" @click="deleteItem">
      <i class="el-icon-delete" style="width: 20px"></i>删除
    </el-button>
    <el-button type="warning" size="small" @click="exportExcel">
      <i class="el-icon-download" style="width: 20px"></i>导出
    </el-button>

    <el-tooltip content="刷新" placement="top">
      <el-button icon="el-icon-refresh" circle style="float: right" size="small" @click="reload"></el-button>
    </el-tooltip>

    <el-tooltip content="隐藏搜索" placement="top">
      <el-button icon="el-icon-search" circle style="float: right" size="small" @click="toggleSearch"></el-button>
    </el-tooltip>


    <el-table
        :data="rooms"
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{background:'#F8F8F9','text-align':'center',color:'#000'}"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @select="selectRoomOneId"
        @select-all="selectRoomAllIds">
      <el-table-column type="selection"></el-table-column>
      <el-table-column type="index" label="序号">
        <template slot-scope="scope">
          {{ getIndex(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column
          prop="roomId"
          label="房屋id"
          v-if="false"
      >
      </el-table-column>
      <el-table-column
          prop="communityName"
          label="小区名称"
      >
      </el-table-column>
      <el-table-column
          prop="buildingName"
          label="楼栋名称"
      >
      </el-table-column>
      <el-table-column
          prop="unitName"
          label="单元名称"
      >
      </el-table-column>
      <el-table-column
          prop="roomLevel"
          label="楼层"
      >
      </el-table-column>
      <el-table-column
          prop="roomName"
          label="房屋名称"
      >
      </el-table-column>
      <el-table-column
          prop="roomCode"
          width="210px"
          label="房屋编号"
      >
      </el-table-column>
      <el-table-column
          prop="roomAcreage"
          label="房屋建筑面积">
      </el-table-column>
      <el-table-column
          prop="roomCost"
          label="算费系数">
      </el-table-column>
      <el-table-column
          prop="roomStatusLabel"
          label="房屋状态">
      </el-table-column>
      <el-table-column
          prop="roomIsShopLabel"
          label="是否商铺">
      </el-table-column>
      <el-table-column
          prop="roomSCommercialHouseLabel"
          label="是否商品房">
      </el-table-column>
      <el-table-column
          prop="roomHouseTypeLabel"
          label="房屋户型">
      </el-table-column>
      <el-table-column
          width="170px"
          prop="formattedCreateTime"
          label="创建时间">
      </el-table-column>
      <el-table-column
          prop="remark"
          label="备注">
      </el-table-column>
      <el-table-column
          width="100px"
          fixed="right"
          label="操作"
      >
        <template slot-scope="scope">
          <el-tooltip content="修改" placement="top">
            <el-button type="primary" icon="el-icon-edit" @click="editRoom(scope.row)"
                       circle size="small"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="danger" icon="el-icon-delete" circle @click="open(scope.row.roomId)"
                       size="small"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <div id="pagination">
      <!--分页按钮-->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[2,3,4]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--弹出式表单-->
    <el-dialog :title="room.roomId==null?'添加房屋':'修改房屋'" :visible.sync="dialogFormVisible"
               :before-close="handleClose">
      <el-form :model="room" :rules="rules" ref="form">
        <el-input v-model="room.communityId" autocomplete="off" type="hidden"></el-input>

        <el-form-item label="楼栋/单元" :label-width="formLabelWidth" prop="buildingId">
          <!--          <div class="block">-->
          <!--            <span class="demonstration">楼栋/单元</span>-->
          <el-cascader
              v-model="options"
              :options="value"
              :props="props"
              @change="handleChange">
          </el-cascader>
          <!--          </div>-->
        </el-form-item>

        <el-form-item label="楼层" :label-width="formLabelWidth" prop="roomLevel">
          <el-input v-model="room.roomLevel" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="房间名称" :label-width="formLabelWidth" prop="roomName">
          <el-input v-model="room.roomName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="建筑面积" :label-width="formLabelWidth" prop="roomAcreage">
          <el-input v-model="room.roomAcreage" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="算费系数" :label-width="formLabelWidth" prop="roomCost">
          <el-input v-model="room.roomCost" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="房屋状态" :label-width="formLabelWidth" prop="roomStatus">
          <el-select v-model="room.roomStatus" placeholder="请选择">
            <el-option
                v-for=" item in roomStatus"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否商铺" :label-width="formLabelWidth">
          <el-radio v-model="room.roomIsShop" label="Y">是</el-radio>
          <el-radio v-model="room.roomIsShop" label="N">否</el-radio>
        </el-form-item>

        <el-form-item label="是否商品房" :label-width="formLabelWidth">
          <el-radio v-model="room.roomSCommercialHouse" label="Y">是</el-radio>
          <el-radio v-model="room.roomSCommercialHouse" label="N">否</el-radio>
        </el-form-item>


        <el-form-item label="房屋户型" :label-width="formLabelWidth" prop="roomHouseType">
          <el-select v-model="room.roomHouseType" placeholder="请选择">
            <el-option
                v-for=" item in roomHouseType"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="room.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false,clearForm()">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false,saveAndEditStudent('form')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<style scoped>

#pagination {
  text-align: center;
}

</style>
